/*
 * @Author: Author && Email
 * @Date: 2024-03-17 13:03:48
 * @LastEditors: Author && Email
 * @LastEditTime: 2024-03-17 18:23:23
 * @FilePath: \MDK-ARMd:\WorkSpace\PRJ\Washing_machine\software\Washing_machine_V1\User\bsp\bsp_encoder.c
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
#include "bsp_encoder.h"
#include "string.h"

encoder_t g_encoder;

/**
 * @description: 编码器初始化
 * @return {*}
 */
void bsp_encoder_init(void)
{
	HAL_TIM_Encoder_Start(&htim1, TIM_CHANNEL_ALL);	/* 编码器模式启动 */
	/* 开启定时器1更新中断 用于编码器计数溢出处理 */
	__HAL_TIM_CLEAR_IT(&htim1, TIM_IT_UPDATE);
	HAL_TIM_Base_Start_IT(&htim1);
	/* 变量初始化 */
	memset(&g_encoder, 0, sizeof(g_encoder));
}

/**
 * @description: 编码器溢出处理
 * @return {*}
 */
void bsp_encoder_over_flow_isr(void)
{
	if(__HAL_TIM_IS_TIM_COUNTING_DOWN(&htim1) == 1)	/* 下溢 */
	{
		g_encoder.overflow_cnt--;
	}
	else	/* 上溢 */
	{
		g_encoder.overflow_cnt++;
	}
}

/**
 * @description: 编码器脉冲以及速度计算 1ms周期调用
 * @return {*}
 */
void bsp_encoder_task(void)
{
	static int32_t pluse_last_cnt = 0;
	static uint8_t ticker = 0;

	ticker++;
	if(ticker >= 100)	/* 100ms */
	{
		ticker = 0;
		g_encoder.dir = __HAL_TIM_IS_TIM_COUNTING_DOWN(&htim1);	/* 获得旋转方向 */
		g_encoder.pulse_cnt = __HAL_TIM_GET_COUNTER(&htim1) + (g_encoder.overflow_cnt * 65535);	/* 脉冲计数 */
		
		if(g_encoder.dir == FWD)
		{
			g_encoder.speed = (g_encoder.pulse_cnt - pluse_last_cnt) * 100 / ENCODER_TOTAL_RESOLUTION * 10 * 60 / 100;	/* 转速计算 */
		}
		else if(g_encoder.dir == REV)
		{
			g_encoder.speed = (pluse_last_cnt - g_encoder.pulse_cnt) * 100 / ENCODER_TOTAL_RESOLUTION * 10 * 60 / 100;	/* 转速计算 */
		}
		

		pluse_last_cnt = g_encoder.pulse_cnt;
	}
}

